package com.etop.weiway.wxmanage.controller;

import com.alibaba.fastjson.JSON;
import com.etop.weiway.basic.controller.BaseController;
import com.etop.weiway.commons.annotation.AccountRequired;
import com.etop.weiway.commons.web.Pager;
import com.etop.weiway.wxmanage.entity.MaterialMutinews;
import com.etop.weiway.wxmanage.entity.MaterialText;
import com.etop.weiway.wxmanage.entity.WeixinMenu;
import com.etop.weiway.wxmanage.service.MaterialService;
import com.etop.weiway.wxmanage.service.WeixinMenuService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 微信菜单管理控制器
 * Created by Jeremie on 2014/12/15.
 */
@Controller
@RequestMapping("/wxmanager/menu")
public class WeixinMenuController extends BaseController {
    @Autowired
    private WeixinMenuService weixinMenuService;
    @Autowired
    private MaterialService materialService;


    /**
     * 注入微信菜单
     *
     * @param id
     * @return
     * @throws Exception
     */
    @ModelAttribute(value = "weixinMenu")
    public WeixinMenu get(@RequestParam(required = false) Integer id)
            throws Exception {
        if (id != null && id > 0) {
            return weixinMenuService.loadWeixinMenu(id);
        } else {
            return new WeixinMenu();
        }
    }

    /**
     * 跳转到微信菜单信息添加修改页面
     *
     * @param weixinMenu
     * @param model
     * @return
     */
    @RequiresPermissions("menu:menu")
    @AccountRequired
    @RequestMapping(value = "/edit", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
    public String form(@ModelAttribute(value = "weixinMenu") WeixinMenu weixinMenu,
                       Model model, HttpSession session) throws Exception {
        model.addAttribute("weixinMenu", weixinMenu);
        model.addAttribute("parentMenu", weixinMenuService.getParentWeinxinMenu((Integer) session.getAttribute("currentAccoutId"), weixinMenu.getParent() == null ? 0 : weixinMenu.getParent().getId()));
        //以下用于修改菜单
        if("click".equals(weixinMenu.getMenuType())&&weixinMenu.getMaterialType()!=null){
            switch(weixinMenu.getMaterialType().toLowerCase()){
                case "text":
                    MaterialText materialText = new MaterialText();
                    materialText.setContent(weixinMenu.getContent());
                    model.addAttribute("materialText",materialText);
                    break;
                case "image":
                    model.addAttribute("materialImage", materialService.loadMaterialImage(weixinMenu.getMaterialId()));
                    break;
                case "video":
                    model.addAttribute("materialVideo", materialService.loadMaterialVideo(weixinMenu.getMaterialId()));
                    break;
                case "voice":
                    model.addAttribute("materialVoice", materialService.loadMaterialVoice(weixinMenu.getMaterialId()));
                    break;
                case "news":
                    model.addAttribute("materialNews", materialService.loadMaterialNews(weixinMenu.getMaterialId()));
                    break;
                case "mutinews":
                    MaterialMutinews materialMutinews = materialService.loadMaterialMutinews(weixinMenu.getMaterialId());
                    model.addAttribute("materialNewses", JSON.toJSONString(materialMutinews.getMaterialNewses(), true));
                    break;
                default: break;
            }
        }
        return "/home/wxmanage/base/weixinMenu/edit";
    }

    /**
     * 保存或更新微信菜单信息
     *
     * @param weixinMenu
     * @param model
     * @param oldMenuKey
     * @param redirectAttributes
     * @return
     * @throws Exception
     */
    @RequiresPermissions("menu:menu")
    @AccountRequired
    @RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "text/html; charset=utf-8")
    public String save(WeixinMenu weixinMenu,int parentId, Model model, String oldMenuKey, RedirectAttributes redirectAttributes, HttpSession session) throws Exception {
        //检测名称是否存在
        if (!"".equals(weixinMenu.getMenuKey()) && !oldMenuKey.equals(weixinMenu.getMenuKey())
                && weixinMenuService.loadWeixinMenuByMenuKey(weixinMenu.getMenuKey()) != null) {
            addMessage(model, ERROR, "保存菜单<" + weixinMenu.getMenuKey()
                    + ">失败，该关键词已存在！");
            weixinMenu.setMenuKey(oldMenuKey);
            return form(weixinMenu, model, session);
        }
        weixinMenuService.saveWeixinMenu(weixinMenu,parentId);
        addMessage(redirectAttributes, SUCCESS, "保存微信菜单<" + weixinMenu.getTitle() + ">成功！");
        return "redirect:/wxmanager/menu/list";
    }

    /**
     * 分页列出微信菜单信息
     *
     * @param weixinMenu
     * @param request
     * @param response
     * @param model
     * @return
     * @throws Exception
     */
    @RequiresPermissions("menu:menu")
    @AccountRequired
    @RequestMapping(value = "/list", produces = "text/html; charset=utf-8")
    public String listWeixinMenu(@ModelAttribute(value = "weixinMenu") WeixinMenu weixinMenu,
                                 HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) throws Exception {
        Pager<WeixinMenu> weixinMenuPager;
        if (session.getAttribute("currentAccoutId") != null)
            weixinMenuPager = weixinMenuService.getWeixinMenuByPage(new Pager<>(request, response), weixinMenu.getTitle(), (Integer) session.getAttribute("currentAccoutId"));
        else
            weixinMenuPager = new Pager<>(1, 10);
        model.addAttribute(weixinMenuPager);
        model.addAttribute("search",weixinMenu.getTitle());
        return "/home/wxmanage/base/weixinMenu/list";
    }

    /**
     * 删除微信菜单信息
     *
     * @param id
     * @param redirectAttributes
     * @return
     * @throws Exception
     */
    @RequiresPermissions("menu:menu")
    @AccountRequired
    @RequestMapping(value = "/delete", produces = "text/html; charset=utf-8")
    public String deleteWeixinMenu(int id, RedirectAttributes redirectAttributes,HttpSession session) throws Exception {
        weixinMenuService.deleteWeixinMenuById(id);
        addMessage(redirectAttributes, SUCCESS, "删除菜单成功！");
        return "redirect:/wxmanager/menu/list";
    }


    /**
     * 生成微信自定义菜单
     *
     * @param redirectAttributes
     * @param accountId
     * @return
     */
    @RequiresPermissions("menu:menu")
    @AccountRequired
    @RequestMapping(value = "/createMenu", produces = "text/html; charset=utf-8")
    public String createMenu(RedirectAttributes redirectAttributes, Integer accountId,HttpSession session) throws Exception {
        List<WeixinMenu> weixinMenus = weixinMenuService.getWeixinMenuByAccountId(accountId);
        Map<String,String> result = weixinMenuService.generateWeixinMenu(weixinMenus, accountId);
        addMessage(redirectAttributes,result.get("type"),result.get("message"));
        return "redirect:/wxmanager/menu/list";
    }
}
